package com.cxb.utils;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.cxb.entity.ApnNode;
 
/**
 * Apn基础类，封装关于Apn操作的常用方法
 * 
 * @Description: Apn基础类，封装关于Apn操作的常用方法
 * 
 * @FileName: ApnService.java
 * 
 * @Package com.apn.util
 * 
 * @Author Hanyonglu
 * 
 * @Date 2012-3-27 上午11:06:40
 * 
 * @Version V1.0
 */
public class ApnUtility { 
	// 列表数据源
	protected static ArrayList<HashMap<String, String>> apn_list = null;

	// APN列表资源
	protected static Uri APN_LIST_URI = Uri
			.parse("content://telephony/carriers");

	// 默认APN资源
	protected static Uri PREFERRED_APN_URI = Uri
			.parse("content://telephony/carriers/preferapn");

	private String tag = "ApnUtility";// 标签

	private int OLD_APN_ID = -1, OLD_NETWORK_TYPE = -1, NEW_APN_ID = -1,
			EM_APN_ID = -1;

	private String NUMERIC = "";

	private ApnNode YIDONG_APN = null, YIDONG_OLD_APN = null,
			CHINAMOBILE_APN = null;

	// 网络类型
	private static final int NET_3G = 1, NET_WIFI = 2, NET_OTHER = -1;

	private Context context;

	public ApnUtility(Context context) {
		super();
		this.context = context;
	}

	/**
	 * 得到SIM卡上的信息
	 */
	protected void GetNumeric() {
		TelephonyManager iPhoneManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		NUMERIC = iPhoneManager.getSimOperator();
	}

	/**
	 * @Name: GetApnList
	 * @Description: 获得APN列表
	 * @param @return 设定文件
	 * @return ArrayList<HashMap<String,String>> 返回类型
	 * @throws
	 */
	protected ArrayList<HashMap<String, String>> GetApnList() {
		apn_list = new ArrayList<HashMap<String, String>>();
		/*
		 * / //建议输入projection字段，提查询效率 String projection[] = {
		 * "_id,name,apn,port,user,server,password,mmsc,mmsproxy,mmsport,mcc,mnc,numeric,type"
		 * }; Cursor cr = context.getContentResolver().query(APN_LIST_URI,
		 * projection, null, null, null); /
		 */
		Cursor cr = context.getContentResolver().query(APN_LIST_URI, null,
				null, null, null);
		// */
		while (cr != null && cr.moveToNext()) {
			Log.v(tag,
					cr.getString(cr.getColumnIndex("_id")) + "  "
							+ cr.getString(cr.getColumnIndex("name")) + "  "
							+ cr.getString(cr.getColumnIndex("type")) + "  ");
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("id", cr.getString(cr.getColumnIndex("_id")));
			map.put("apn", cr.getString(cr.getColumnIndex("name")));
			map.put("name", cr.getString(cr.getColumnIndex("type")));
			apn_list.add(map);
		}

		if (apn_list.size() > 0) {
			return apn_list;
		} else {
			return null;
		}
	}

	/**
	 * 获得网络连接管理权
	 */
	private ConnectivityManager getConnectManager() {
		ConnectivityManager m_ConnectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		return m_ConnectivityManager;
	}

	/**
	 * 获得当前联网类型wifi or mobile
	 * 
	 * @return
	 */
	private int getNetWorkType() {
		if (getConnectManager() != null) {
			NetworkInfo networkInfo = getConnectManager()
					.getActiveNetworkInfo();
			if (networkInfo != null)
				return networkInfo.getType();
			return -1;
		} else {
			return -1;
		}
	}

	/**
	 * 获取当前网络类型
	 * 
	 * @return
	 */
	public int GetCurrentNetType() {
		int net_type = getNetWorkType();

		if (net_type == ConnectivityManager.TYPE_MOBILE) {
			return NET_3G;
		} else if (net_type == ConnectivityManager.TYPE_WIFI) {
			return NET_WIFI;
		}

		return NET_OTHER;
	}

	/**
	 * 获取当前使用的APN信息
	 * 
	 * @return
	 */
	public ApnNode getDefaultAPN() {
		String id = "";
		String apn = "";
		String name = "";
		String type = "";
		ApnNode apnNode = new ApnNode();
		Cursor mCursor = context.getContentResolver().query(PREFERRED_APN_URI,
				null, null, null, null);

		if (mCursor == null) {
			return null;
		}

		while (mCursor != null && mCursor.moveToNext()) {
			id = mCursor.getString(mCursor.getColumnIndex("_id"));
			name = mCursor.getString(mCursor.getColumnIndex("name"));
			apn = mCursor.getString(mCursor.getColumnIndex("apn"))
					.toLowerCase();
			type = mCursor.getString(mCursor.getColumnIndex("type"))
					.toLowerCase();
		}

		try {
			OLD_APN_ID = Integer.valueOf(id);
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(context, "请配置好APN列表！", Toast.LENGTH_LONG).show();
		}

		apnNode.setName(name);
		apnNode.setApn(apn);
		apnNode.setType(type);

		return apnNode;
	}

	/**
	 * 根据apnId将设置的APN选中
	 * 
	 * @param apnId
	 * @return
	 */
	public boolean setDefaultApn(int apnId) {
		boolean res = false;
		ContentResolver resolver = context.getContentResolver();
		ContentValues values = new ContentValues();
		values.put("apn_id", apnId);

		try {
			resolver.update(PREFERRED_APN_URI, values, null, null);
			Cursor c = resolver.query(PREFERRED_APN_URI, new String[] { "name",
					"apn" }, "_id=" + apnId, null, null);
			if (c != null) {
				res = true;
				c.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return res;
	}

	/**
	 * 利用ContentProvider将添加的APN数据添加进入数据库
	 * 
	 * @return
	 */
	public int AddApn(String name, String apn, String mcc, String mnc) {
		int apnId = -1;
		GetNumeric();
		ContentResolver resolver = context.getContentResolver();
		ContentValues values = new ContentValues();

		values.put("name", name);
		values.put("apn", apn);
		values.put("type", "default,supl");
		values.put("numeric", mcc+mnc);
		values.put("mcc", mcc);
		values.put("mnc", mnc);
		values.put("proxy", "");
		values.put("port", "");
		values.put("mmsproxy", "");
		values.put("mmsport", "");
		values.put("user", "");
		values.put("server", "");
		values.put("password", "");
		values.put("mmsc", "");

		Cursor c = null;

		try {
			Uri newRow = resolver.insert(APN_LIST_URI, values);
			if (newRow != null) {
				c = resolver.query(newRow, null, null, null, null);
				int idindex = c.getColumnIndex("_id");
				c.moveToFirst();
				apnId = c.getShort(idindex);
				Log.d("Robert", "New ID: " + apnId
						+ ": Inserting new APN succeeded!");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (c != null)
			c.close();

		return apnId;

	}

	/**
	 * 删除指定的APN
	 * 
	 * @param id
	 * @return
	 */
	public int Delete_Apn(int id) {
		int deleteId = -1;
		ContentResolver resolver = context.getContentResolver();
		Uri deleteIdUri = ContentUris.withAppendedId(APN_LIST_URI, id);

		try {
			deleteId = resolver.delete(deleteIdUri, null, null);
		} catch (Exception e) {
			return deleteId;
		}

		return deleteId;
	}

	/**
	 * 关闭WIFI网络状态
	 */
	public void closeWifiNetwork() {
		// WifiManager wifiManager =
		// (WifiManager)context.getSystemService(context.WIFI_SERVICE);
		// Log.v("WIFI_STATE", String.valueOf(wifiManager.getWifiState()));
		//
		// if(wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED)
		// wifiManager.setWifiEnabled(false);
	}

	// 编辑APN内容
	public void editApn( String name, String apn, String mcc,
			String mnc) {
		int id = -1;
		Uri uri = Uri.parse("content://telephony/carriers");
		ContentResolver resolver = context.getContentResolver();
		Cursor c = resolver.query(uri, new String[] { "_id", "name", "apn" },
				"apn like '%" + apn + "%'", null, null);
 
		int count=c.getCount();
		// 该项APN存在
		if (c != null && c.moveToNext()) {
			id = c.getShort(c.getColumnIndex("_id"));
			// String name = c.getString(c.getColumnIndex("name"));
			// String apn = c.getString(c.getColumnIndex("apn"));
			//
			// Log.v("APN", id + name + apn);
			// Uri uri1 = Uri.parse("content://telephony/carriers/" + id);

			setDefaultApn(id);
			
		} else {
			// 如果不存在该项APN则进行添加
			setDefaultApn(AddApn(name, apn, mcc, mnc));

		}
		if(c!=null){
			c.close();
		}
	}
}